import {defineStore} from 'pinia'
import {parseToken} from "@/utils/jwt";
import {logoutAxios} from "@/api/user_api";
import {Message} from "@arco-design/web-vue";

export interface userInfoType {
    nick_name: string
    avatar: string  // 头像
    role: number     // 1管理员 2普通用户 3游客
    user_id: number
    token: string
    exp: number // 过期时间需要想x1000
    iss: string
}

const userInfo: userInfoType = {
    nick_name: "",
    avatar: "",
    role: 0,
    user_id: 0,
    token: "",
    exp: 0,
    iss: ""
}

export const useStore = defineStore('counter', {
    state() {
        return {
            theme: true,
            collapse: false, // 后台侧边栏收缩
            userInfo: userInfo,
        }
    },
    actions: {
        setTheme(local?: boolean) {
            if (local !== undefined) {
                this.theme = local
            } else {
                this.theme = !this.theme
            }
            document.documentElement.style.colorScheme = this.themeStr
            document.body.setAttribute('arco-theme', this.themeStr)
            localStorage.setItem('theme', JSON.stringify(this.theme))
        },
        loadTheme() {
            let val = localStorage.getItem('theme')
            if (val === null) {
                return
            }
            try {
                this.theme = JSON.parse(val)
                this.setTheme(this.theme)
            } catch (e) {
                return
            }
        },
        setCollapse(collapse: boolean) {
            this.collapse = collapse
        },
        setToken(token: string) {
            this.userInfo.token = token
            let info = parseToken(token)
            Object.assign(this.userInfo, info)
            this.userInfo.avatar = "http://localhost" + this.userInfo.avatar
            localStorage.setItem('userInfo', JSON.stringify(this.userInfo))
        },
        loadToken() {
            let userInfoStr = localStorage.getItem('userInfo')
            if (userInfoStr === null) {
                return
            }
            try {
                this.userInfo = JSON.parse(userInfoStr)
            } catch (e) {
                this.clearUserInfo()
                return
            }
            let exp = Number(this.userInfo.exp) * 1000
            let nowTime = new Date().getTime()
            if ((exp - nowTime) <= 0) {
                Message.warning("登录已过期")
                this.clearUserInfo()
                return
            }
        },
        async logout() {
            await logoutAxios()
            this.clearUserInfo()
        },
        clearUserInfo() {
            this.userInfo = userInfo
            localStorage.removeItem("userInfo")
        },
    },
    getters: {
        themeStr(): string {
            return this.theme ? "light" : "dark"
        },
        // 判断登录且为管理员
        isAdmin(): boolean {
            return this.userInfo.role === 1
        },
    }
})
